package com.fingard.dsp.bank.directbank.wfccb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 潍坊银行批付查询
 * Created by F on 2019/06/17.
 */
public class WFCCB01BatPayRec extends WFCCB01Base implements IBatPayRec {

    /**
     * 批量代付提交
     *
     * @param p_req1988
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        Connection conn= FGBiz.getLocalDbConn();
        try{
            //======拼接报文======
            //拼接请求报文体
            WFCCB01Header header = new WFCCB01Header();
            header.opname="agencyPay";
            header.serialNo = getQryTransID();
            XmlTextWriter xmlReq = new XmlTextWriter();
            writeReqHeader(xmlReq,header);
            xmlReq.writeStartElement("ReqParam");
            xmlReq.writeElementString("payAccount",p_req1988.ownAct);//付款账号
            xmlReq.writeElementString("payAccountName",p_req1988.ownActName);//付款姓名
            xmlReq.writeElementString("totalNumber",p_req1988.totalNum);//总笔数
            xmlReq.writeElementString("totalAmount",p_req1988.totalAmt);//总金额
            Calendar calendar=Calendar.getInstance();
            calendar.setTime(Format.Date10Format.parse(p_req1988.payDate));
            calendar.add(Calendar.MONTH, -1);
            String dateTime=Format.Date8Format.format(calendar.getTime());
            xmlReq.writeElementString("payMonth",dateTime.substring(0,6));//代发月份yyyyMM  取支付时间上一个月
            xmlReq.writeElementString("currencyType",convertCurToBank(p_req1988.ownCur));//币种
            xmlReq.writeElementString("orderFlowNo",header.serialNo);//指令流水号
            //记录批次号对应的银行支付流水号，供查询状态接口使用
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_req1988.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req1988.reqBatchNO, header.serialNo});
            xmlReq.writeElementString("dscrpCod","0002");//摘要0002-代发工资
            xmlReq.writeElementString("trsDateTime",DateHelper.convertD10toD8(p_req1988.payDate)
                    +p_req1988.payTime.replaceAll(":",""));//交易时间
            int tmpCount=0;
            xmlReq.writeStartElement("tranDetail");
            while (p_req1988.readRecord()){
                tmpCount++;
                xmlReq.writeStartElement("row");
                xmlReq.writeElementString("SalaryId",tmpCount+"");//明细编号
                xmlReq.writeElementString("employeeId",p_req1988.readedDetail.askNumber);//员工编号
                xmlReq.writeElementString("employeeName",p_req1988.readedDetail.recName);//员工姓名
                xmlReq.writeElementString("cardNo",p_req1988.readedDetail.recAct);//员工卡号
                xmlReq.writeElementString("payAmount",p_req1988.readedDetail.payAmount);//金额
                xmlReq.writeElementClosed("comment");//备注
                xmlReq.writeEndElement();
            }
            xmlReq.writeEndElement();
            if(tmpCount!=Integer.parseInt(p_req1988.totalNum)){
                retAts.respCode = "-1";
                retAts.respInfo = "总笔数与循环数不一致";
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.writeRetToATS();
                return retAts;
            }
            xmlReq.writeEndDocument();
            //获取签名数据
            String sign=signnatrue(xmlReq.toXmlString());
            //拼接请求报文
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            header.signedData=sign;
            writeCommonHeader(xmlTextWriter,header);
            xmlTextWriter.directWrite(xmlReq.toXmlString());
            xmlTextWriter.writeEndElement();
            //======拼接报文======
            //发送请求报文
            String[] bankResult = sendToBank(requestBody(header,xmlTextWriter.toXmlString()));
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String respCode = tmpBkReader.getFirstText("/BankData/opRep/hostReturnCode");
                    String respInfo = tmpBkReader.getFirstText("/BankData/opRep/hostErrorMessage");
                    retAts.respCode = "0";
                    retAts.respInfo = respCode+" "+respInfo;
                    retAts.reqSeqID = p_req1988.reqBatchNO;
                    if(success(respCode)){
                        retAts.transState = "000000";
                    }else if(success999(respCode)){
                        retAts.transState = "999999";
                    }else {
                        retAts.transState = respCode;
                    }
                    retAts.payInfoCode = retAts.transState;
                }else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            }else if(bankResult[0].equals(ConnState.FAIL)){
                retAts.respCode = "0";
                retAts.respInfo = bankResult[1];
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = bankResult[0];
            }
            else{
                retAts.respCode = "-1";
                retAts.respInfo = bankResult[1];
            }
        }catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            WriteBankLogLn("批量代发异常："+e);
            e.printStackTrace();
        }finally {
            conn.close();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1988.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        // 返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        Connection conn=FGBiz.getLocalDbConn();
        try {
            //======拼接报文======
            //拼接请求报文体
            WFCCB01Header header = new WFCCB01Header();
            header.opname="agencyPayQry";
            header.serialNo = getQryTransID();
            XmlTextWriter xmlReq = new XmlTextWriter();
            writeReqHeader(xmlReq,header);
            XElement body =new XElement("ReqParam","");
            Map<String, Object> selMap=JDBCHelper.execQuerySingle(conn,SELECTSEQ,new Object[]{p_req1998.reqBatchNO,p_req1998.reqHeader.bankCode});
            if(selMap.size()>0){
                body.addChild(new XElement("orderFlowNo", selMap.get("BANKREQSEQID").toString()));//交易流水号
            }else {
                retAts.respCode ="-1";
                retAts.respInfo = "交易流水号关联映射异常，请检查";
                retAts.writeBeforeDetail();
                retAts.writeAfterDetail();
                return retAts;
            }
            xmlReq.writeXElement(body);
            xmlReq.writeEndDocument();
            //获取签名数据
            String sign=signnatrue(xmlReq.toXmlString());
            //拼接请求报文
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            header.signedData=sign;
            writeCommonHeader(xmlTextWriter,header);
            xmlTextWriter.directWrite(xmlReq.toXmlString());
            xmlTextWriter.writeEndElement();
            //======拼接报文======
            //发送请求报文
            String[] bankResult = sendToBank(requestBody(header,xmlTextWriter.toXmlString()));
            //处理响应报文
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String respCode = tmpBkReader.getFirstText("/BankData/opRep/hostReturnCode");
                    String respInfo = tmpBkReader.getFirstText("/BankData/opRep/hostErrorMessage");
                    if (success(respCode)) {
                        String state=tmpBkReader.getFirstText("/BankData/opRep/RepParam/state");
                        String errorMessage=tmpBkReader.getFirstText("/BankData/opRep/RepParam/errorMessage");
                        if("1".equals(state) || "2".equals(state)){
                            retAts.respCode = "0";
                            retAts.respInfo=respInfo+"："+errorMessage;
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            retAts.writeBeforeDetail();
                            while (tmpBkReader.read("/BankData/opRep/RepParam/tranDetail/row")){
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                tmpRetDetail.payAct = p_req1998.ownAct;
                                tmpRetDetail.payName = "";
                                tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("cardNo");//收款人号
                                tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("employeeName");//收款人名
                                tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("employeeId");//批内流水号
                                tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("payAmount");//金额
                                tmpRetDetail.memo = "";//备注
                                tmpRetDetail.result = tmpBkReader.readedXElement.getSingleText("DetailState");//COMPLETE–成功、FAIL-失败
                                tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        }else{
                            retAts.respCode = "0";
                            retAts.respInfo=respInfo+"："+errorMessage;
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            retAts.transState=state;
                            retAts.payInfoCode=retAts.transState;
                            retAts.writeBeforeDetail();
                        }
                    }else {
                        retAts.respCode = "-1";
                        retAts.respInfo = respInfo;
                    }
                }else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            }else {
                retAts.respCode = "-1";
                retAts.respInfo = bankResult[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }finally {
            conn.close();
        }
        if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }
        if ("-1".equals(retAts.respCode)) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}
